namespace Example.Models
{
    using System;
    using System.Web;
    using Moq;
    using SimpleWebServices;
    using SimpleWebServices.Data;
    using SimpleWebServices.Models;
    using SimpleWebServices.Web;
    using SimpleWebServices.Web.UI.Html;
    using Xunit;

    public sealed class ContactFormFacts
    {
        [Fact]
        public void typedef()
        {
            Assert.True(new ObjectExpectations<ContactForm>()
                .DerivesFrom<FormContainer>()
                .IsConcreteClass()
                .IsSealed()
                .HasDefaultConstructor()
                .XmlRoot("container")
                .Result);
        }

        [Fact]
        public void ctor()
        {
            Assert.NotNull(new ContactForm());
        }

        [Fact]
        public void op_Complete_FormSession()
        {
            FakeRepository.Clear();

            try
            {
                Token token = Token.New();

                FakeRepository.Register<Tenant>(new
                {
                    urn = "urn://simplewebservices.org/tenant/test",
                    xml = "<tenant name='Test' />"
                });
                FakeRepository contacts = FakeRepository.Register<Contact>();
                FakeRepository sessions = FakeRepository.Register<FormSession>();

                var mock = new Mock<HttpContextBase>();
                mock.SetupGet<string>(x => x.Request.RawUrl).Returns("/test/help/contact-us?" + token).Verifiable();
                HttpContextFactory.Mock = mock.Object;

                ContactForm contact = Activator.CreateInstance<ContactForm>().Populated<ContactForm>();
                contact.Form.Update(new FormSession());
                contact.Token = contact.Form.Store(new DataCollection());

                contact.Complete(SimpleWebServices.Data.Record.Retrieve<FormSession>(contact.Token.Value));

                Assert.True((bool)contacts.Xml.CreateNavigator().Evaluate("1=count(/repository/object[@token][@urn]/contact)"));

                Assert.True((bool)sessions.Xml.CreateNavigator().Evaluate("1=count(/repository/object[@token][@urn]/session/data[@completed='true'])"));

                mock.VerifyAll();
            }
            finally
            {
                FakeRepository.Reset();
                HttpContextFactory.Reset();
            }
        }

        [Fact]
        public void op_Complete_FormSessionNull()
        {
            Assert.Throws<ArgumentNullException>(() => new ContactForm().Complete(null as FormSession));
        }

        [Fact]
        public void op_TemplateOfT()
        {
            Assert.NotNull(new ContactForm().Template<ContactForm>());
        }
    }
}